package cn.xiaopengstack.config;

import cn.xiaopengstack.domain.agent.model.entity.ArmoryCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientTypyEnumVO;
import cn.xiaopengstack.domain.agent.service.armory.factory.DefaultArmoryStrategyFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author jiangyangang
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(AiAgentAutoConfigProperties.class)
@ConditionalOnProperty(prefix = "spring.ai.agent.auto-config", name = "enable", havingValue = "true")
public class AiAgentAutoConfiguration implements ApplicationListener<ApplicationReadyEvent> {
    @Resource
    private AiAgentAutoConfigProperties aiAgentAutoConfigProperties;

    @Resource
    private DefaultArmoryStrategyFactory armoryStrategyFactory;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            log.info("AI Agent自动装配开始，配置:{}", aiAgentAutoConfigProperties);
            // 检测配置
            if (!aiAgentAutoConfigProperties.isEnable()) {
                log.info("AI Agent自动装配未启用");
                return;
            }

            // 解析客户端ID
            List<String> clientIds = aiAgentAutoConfigProperties.getClientIds();
            ArmoryCommandEntity commandEntity = ArmoryCommandEntity.builder()
                    .commandType(AiAgentEnumVO.AI_CLIENT.getCode())
                    .commandIdList(clientIds)
                    .build();

            String result = armoryStrategyFactory.armoryStrategyHandler().apply(commandEntity, new DefaultArmoryStrategyFactory.DynamicContext());

            log.info("AI Agent自动装配完成{}", result);

        } catch (Exception e) {
            log.error("AI Agent自动装配异常", e);
        }
    }
}
